﻿using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    static class ReferenceHelper
    {
        public static FloatingColumnReference GetFloatingColumnReference (Worksheet ws, RgceLocRel  RgceLocRel, Cell cell)
        {
            if (!RgceLocRel.IsAbsoluteColumn)
            {
                short u = (short) RgceLocRel.ColumnIndex;
                var columnIndex = cell.Column.Index + u;
                if (columnIndex > 0x00FF)
                    columnIndex -= 0x100;
                if (columnIndex < 0x00)
                    columnIndex += 0x100;
                var offset = columnIndex - cell.Column.Index;
                return new FloatingColumnReference(ws, offset, RgceLocRel.IsAbsoluteColumn);
            }
            return new FloatingColumnReference(ws, (short)RgceLocRel.ColumnIndex, RgceLocRel.IsAbsoluteColumn);
        }
        public static AnchoredColumnReference GetAnchoredColumnReference(Worksheet ws, RgceLocRel rgceLocRel, Cell cell)
        {
            if (rgceLocRel.IsAbsoluteColumn)
                return new AnchoredColumnReference(ws.Columns[rgceLocRel.ColumnIndex], rgceLocRel.IsAbsoluteColumn);
            return new AnchoredColumnReference(ws.Columns[rgceLocRel.ColumnIndex + cell.Column.Index], rgceLocRel.IsAbsoluteColumn);
        }

        public static AnchoredRowReference GetAnchoredRowReference(Worksheet ws, RgceLocRel rgceLocRel, Cell cell)
        {
            if (rgceLocRel.IsAbsoluteRow)
                return new AnchoredRowReference(ws.Rows[rgceLocRel.RowIndex], rgceLocRel.IsAbsoluteColumn);
            return new AnchoredRowReference(ws.Rows[rgceLocRel.RowIndex + cell.Row.Index], rgceLocRel.IsAbsoluteRow);
        }
    }
}